package com.feimt.interceptor;


import com.alibaba.fastjson.JSON;
import com.feimt.common.BaceContent;
import com.feimt.common.PathMatcher;
import com.feimt.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 1. 实现接口
 * 2. 被容器管理
 * 3. 配置拦截路径
 */
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {
    /*前置*/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1. 获取请求路径
        String requestURI = request.getRequestURI();
//        log.info("requestURI:{}",requestURI);
        //2. 页面放行、去登录、登出、日志、不需要登录就能访问的页面-放行
        boolean check = PathMatcher.check(requestURI);
        if(check){
//            log.info("静态资源放行：{}",requestURI);
            return true;
        }
        // 3. 判断是否登录
        HttpSession session = request.getSession();
        Object o = session.getAttribute("auth");
        if(o != null){
            log.info("登录成功：{}",requestURI);
            BaceContent.setThreadLocal((Long) o);
//            System.err.println("auth线程ID:"+Thread.currentThread().getId());
            return true;
        }
        // 4. 没有登录，拦截
        response.setStatus(401);
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;
    }

    /*后置*/
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
    /*最后*/
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
